<template>
  <BasicModal v-bind="$attrs" @register="registerModal" title="上架的门店" @ok="handleSubmit" width="650px" destroyOnClose>
    <BasicTable ref="tableRef" @register="registerTable" />
  </BasicModal>
</template>
<script lang="ts" setup>
  import { ref, computed, toRaw } from "vue"
  import { BasicModal, useModalInner } from "/@/components/Modal"
  import { goodsUpStockColumns } from "./goods.data"
  import { updatePublishStatus } from "./goods.api"
  import { BasicTable, FormSchema, useTable } from "/@/components/Table"
  import { useListPage } from "/@/hooks/system/useListPage"
  import { listStore } from "/@/api/misc/store"

  const searchFormSchema: FormSchema[] = [
    {
      field: "name",
      label: "",
      colProps: { span: 12 },
      componentProps: {
        placeholder: "请输入门店名称",
      },
      component: "Input",
    },
  ]

  const emit = defineEmits(["register", "success"])
  const goodsId = ref()
  const tableRef = ref()
  const tenantIds = ref<any[]>([])
  const isShow = ref<boolean>(false)
  const [registerTable, { setProps, reload, setSelectedRowKeys, getSelectRowKeys }] = useTable({
    api: listStore,
    beforeFetch: (params) => {
      params.tenantIds = isShow.value ? tenantIds.value.join(",") : ""
    },
    immediate: false,
    formConfig: {
      baseColProps: { lg: 12, md: 12, xl: 12, xxl: 12 },
      wrapperCol: { lg: 24, md: 24 },
      baseRowStyle: {
        marginBottom: "-15px",
        marginTop: "-15px",
      },
      schemas: searchFormSchema,
      showResetButton: false,
      showSubmitButton: false,
    },
    rowSelection: {
      type: "checkbox",
    },
    columns: goodsUpStockColumns,
    size: "small",
    pagination: false,
    striped: true,
    useSearchForm: true,
    showTableSetting: false,
    canResize: false,
    bordered: false,
    showIndexColumn: false,
    tableSetting: { fullScreen: true },
    showActionColumn: false,
    rowKey: "id",
  })

  const tempId = ref("")
  const [registerModal, { setModalProps, closeModal }] = useModalInner(async (data) => {
    tenantIds.value = data.record?.tenantIds || []
    console.log("data", data)
    // 是否只查看
    isShow.value = !!data.isShow
    goodsId.value = data.record?.id
    if (isShow.value) {
      setProps({
        rowSelection: undefined,
      })
    }
    setModalProps({ confirmLoading: false, canFullscreen: false, draggable: false })
    reload()
    setSelectedRowKeys(tenantIds.value)
  })

  async function handleSubmit(v) {
    try {
      await updatePublishStatus({ id: goodsId.value, tenantIds: toRaw(getSelectRowKeys()) })
      setModalProps({ confirmLoading: true })
      closeModal()
      emit("success")
    } finally {
      setModalProps({ confirmLoading: false })
    }
  }
</script>
